<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      ref="dataForm"
      v-loading="loading"
      @keyup.enter.native="clickOnConfirm()"
    >
      <el-form-item
        :label="$t('mike.sn8')"
        prop="sn8">
        <sn8-select :sn8.sync="dataForm.sn8"/>

      </el-form-item>

      <el-form-item
        :label="$t('model.name')"
        prop="name">
        <el-input
          placeholder="请输入名称"
          v-model="dataForm.name"/>
      </el-form-item>

      <el-form-item
        :label="$t('mike.link')"
        prop="link">
        <el-input
          placeholder="请输入链接，如:baidu.com,bing.com"
          v-model="dataForm.link"
        >
          <!--                    <template slot="prepend">http://</template>-->
        </el-input>
      </el-form-item>

      <el-form-item
        label="首页主图"
        prop="url">
        <el-upload
          :file-list="imgFileList"
          :limit="1"
          :multiple="false"
          :on-exceed="handleImgFileExceed"
          :on-preview="onImgPreview"
          :on-remove="onImgRemove"
          :on-success="onImgUploadSuccess"
          accept="image/png, image/jpeg"
          action="http://47.106.93.196:8200/cloud-menu/midea/menu/file/upload"
          list-type="picture-card"
        >
          <i class="el-icon-plus"/>
        </el-upload>
      </el-form-item>
    </el-form>

    <template slot="footer">
      <el-button
        :loading="requesting"
        @click="visible = false">{{
          $t("cancel")
        }}</el-button>
      <el-button
        :loading="requesting"
        @click="clickOnConfirm()"
        type="primary"
      >{{ $t("confirm") }}
      </el-button>
    </template>

    <el-dialog
      :append-to-body="true"
      :visible.sync="previewDialogVisible">
      <img
        :src="previewImgUrl"
        alt=""
        width="100%" >
    </el-dialog>
  </el-dialog>
</template>

<script>
import mixinViewModule from '@/mixins/mike.view-module'

import { isURL } from '@/utils/validate'
import Sn8Select from '@/components/sn8.select'

export default {
  name: 'ActivityAddOrUpdate',
  components: { Sn8Select },
  mixins: [mixinViewModule],
  data () {
    return {
      previewImgUrl: '',
      previewDialogVisible: false,
      visible: false,
      loading: false,
      requesting: false,
      imgFileList: [],
      dataForm: {
        createTime: '',
        descri: '',
        ext: '',
        flag: 0,
        id: '',
        link: '',
        name: '',
        recommendSort: 0,
        sn8: '',
        tag: '',
        totalCounts: 0,
        url: ''
      }
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],

        sn8: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        url: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        link: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              console.log(value)
              let str = value.trim()
              if (!str || str.length <= 0) {
                callback(new Error('请输入链接'))
                return
              }

              if (!isURL(str)) {
                callback(new Error('请按照正确的链接格式输入'))
                return
              }
              callback()
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    visible (newValue, oldValue) {
      if (!newValue) {
        this.$refs['dataForm'].resetFields()
        this.imgFileList = []
        this.previewImgUrl = ''
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.imgFileList = []

        if (this.dataForm.id) {
          this.getActivity()
        }
      })
    },
    getActivity () {
      if (this.loading) {
        return
      }
      this.loading = true

      this.$http
        .post(
          `${this.mikeNetworkBase}/midea/menu/piclink/get/${this.dataForm.id}`
        )
        .then(({ data: res }) => {
          if (res.code !== 200) {
            this.$message.error(res.data)
            return
          }
          this.dataForm = res.data

          if (this.dataForm.url && this.dataForm.url.length > 0) {
            this.imgFileList = [
              { name: this.dataForm.url, url: this.dataForm.url }
            ]
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    onImgPreview () {
      this.previewImgUrl = this.dataForm.url
      this.previewDialogVisible = true
    },
    onImgUploadSuccess (response, file, fileList) {
      if (response.code !== 200) {
        this.dataForm.url = ''
        return
      }
      this.dataForm.url = response.data
    },
    onImgRemove () {
      this.dataForm.url = ''
    },
    handleImgFileExceed (files, fileList) {
      this.$message.warning(`只能设置一张图片哦`)
    },
    clickOnConfirm () {
      // validate

      this.$refs['dataForm'].validate(valid => {
        if (!valid) {
          return false
        }
        if (this.requesting) {
          return
        }

        this.requesting = true

        this.$http
          .post(`${this.mikeNetworkBase}midea/menu/piclink/save`, this.dataForm)
          .then(({ data: res }) => {
            if (res.code !== 200) {
              return this.$message.error('请求失败')
            }
            this.$message({
              message: this.$t('prompt.success'),
              type: 'success',
              duration: 500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          })
          .catch(() => {})
          .finally(() => {
            this.requesting = false
          })
      })
    }
  }
}
</script>

<style scoped></style>
